<template>
	<view class="register-container">
		<view class="header">
			<view class="back-btn" @tap="goBack">
				<text class="back-icon">‹</text>
			</view>
			<text class="title">用户注册</text>
		</view>
		
		<view class="form">
			<view class="input-group">
				<text class="label">用户名</text>
				<input type="text" v-model="formData.username" placeholder="请输入用户名（字母、数字，5-20位）" />
				<text class="error" v-if="errors.username">{{ errors.username }}</text>
			</view>
			
			<view class="input-group">
				<text class="label">密码</text>
				<input type="password" v-model="formData.password" placeholder="请输入密码（至少6位）" />
				<text class="error" v-if="errors.password">{{ errors.password }}</text>
			</view>
			
			<view class="input-group">
				<text class="label">确认密码</text>
				<input type="password" v-model="formData.confirmPassword" placeholder="请再次输入密码" />
				<text class="error" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</text>
			</view>
			
			<view class="input-group">
				<text class="label">电子邮箱</text>
				<input type="text" v-model="formData.email" placeholder="请输入电子邮箱" />
				<text class="error" v-if="errors.email">{{ errors.email }}</text>
			</view>
			
			<view class="input-group">
				<text class="label">手机号码</text>
				<input type="number" v-model="formData.phone" placeholder="请输入手机号码" />
				<text class="error" v-if="errors.phone">{{ errors.phone }}</text>
			</view>
			
			<view class="input-group">
				<text class="label">真实姓名（选填）</text>
				<input type="text" v-model="formData.real_name" placeholder="请输入真实姓名" />
			</view>
			
			<view class="agreement">
				<checkbox-group @change="handleAgreementChange">
					<label>
						<checkbox value="agreed" :checked="formData.agreed" />
						<text>我已阅读并同意</text>
						<text class="link" @tap="showAgreement">《用户协议》</text>
						<text>和</text>
						<text class="link" @tap="showPrivacy">《隐私政策》</text>
					</label>
				</checkbox-group>
				<text class="error" v-if="errors.agreed">{{ errors.agreed }}</text>
			</view>
			
			<button class="register-btn" @tap="handleRegister" :disabled="loading">
				{{ loading ? '注册中...' : '立即注册' }}
			</button>
			
			<view class="login-entry">
				<text>已有账号？</text>
				<text class="login-link" @tap="goToLogin">返回登录</text>
			</view>
		</view>
	</view>
</template>

<script>
import api from '../common/api.js';

export default {
	data() {
		return {
			formData: {
				username: '',
				password: '',
				confirmPassword: '',
				email: '',
				phone: '',
				real_name: '',
				agreed: false
			},
			errors: {},
			loading: false
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 前往登录页
		goToLogin() {
			uni.navigateBack();
		},
		
		// 处理协议同意变更
		handleAgreementChange(e) {
			this.formData.agreed = e.detail.value.length > 0;
		},
		
		// 显示用户协议
		showAgreement() {
			uni.showModal({
				title: '用户协议',
				content: '这是用户协议内容，请仔细阅读...',
				confirmText: '我已阅读',
				showCancel: false
			});
		},
		
		// 显示隐私政策
		showPrivacy() {
			uni.showModal({
				title: '隐私政策',
				content: '这是隐私政策内容，请仔细阅读...',
				confirmText: '我已阅读',
				showCancel: false
			});
		},
		
		// 验证表单
		validateForm() {
			this.errors = {};
			let isValid = true;
			
			// 验证用户名
			if (!this.formData.username) {
				this.errors.username = '请输入用户名';
				isValid = false;
			} else if (!/^[a-zA-Z0-9]{5,20}$/.test(this.formData.username)) {
				this.errors.username = '用户名须为5-20位字母或数字';
				isValid = false;
			}
			
			// 验证密码
			if (!this.formData.password) {
				this.errors.password = '请输入密码';
				isValid = false;
			} else if (this.formData.password.length < 6) {
				this.errors.password = '密码长度不能少于6位';
				isValid = false;
			}
			
			// 验证确认密码
			if (!this.formData.confirmPassword) {
				this.errors.confirmPassword = '请确认密码';
				isValid = false;
			} else if (this.formData.password !== this.formData.confirmPassword) {
				this.errors.confirmPassword = '两次输入的密码不一致';
				isValid = false;
			}
			
			// 验证邮箱
			if (!this.formData.email) {
				this.errors.email = '请输入电子邮箱';
				isValid = false;
			} else if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.formData.email)) {
				this.errors.email = '请输入有效的电子邮箱';
				isValid = false;
			}
			
			// 验证手机号
			if (!this.formData.phone) {
				this.errors.phone = '请输入手机号码';
				isValid = false;
			} else if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
				this.errors.phone = '请输入有效的手机号码';
				isValid = false;
			}
			
			// 验证用户协议
			if (!this.formData.agreed) {
				this.errors.agreed = '请阅读并同意用户协议和隐私政策';
				isValid = false;
			}
			
			return isValid;
		},
		
		// 处理注册请求
		handleRegister() {
			// 表单验证
			if (!this.validateForm()) {
				uni.showToast({
					title: '请完善注册信息',
					icon: 'none'
				});
				return;
			}
			
			// 设置加载状态
			this.loading = true;
			
			// 构造请求数据
			const userData = {
				username: this.formData.username,
				password: this.formData.password,
				email: this.formData.email,
				phone: this.formData.phone,
				real_name: this.formData.real_name || ''
			};
			
			// 发送注册请求
			api.register(userData)
				.then(res => {
					if (res.statusCode === 200 && res.data.success) {
						// 注册成功
						uni.showToast({
							title: '注册成功',
							icon: 'success',
							duration: 2000
						});
						
						// 跳转到登录页
						setTimeout(() => {
							uni.navigateBack();
						}, 2000);
					} else {
						// 注册失败
						const errorMsg = res.data.message || '注册失败，请稍后重试';
						
						// 如果是用户名或邮箱已存在的错误，显示在对应字段下
						if (errorMsg.includes('用户名已存在')) {
							this.errors.username = errorMsg;
						} else if (errorMsg.includes('邮箱已存在')) {
							this.errors.email = errorMsg;
						} else if (errorMsg.includes('手机号已存在')) {
							this.errors.phone = errorMsg;
						} else {
							// 其他错误，显示toast
							uni.showToast({
								title: errorMsg,
								icon: 'none'
							});
						}
					}
				})
				.catch(err => {
					console.error('注册请求失败:', err);
					uni.showToast({
						title: '网络错误，请检查网络连接',
						icon: 'none'
					});
				})
				.finally(() => {
					this.loading = false;
				});
		}
	}
}
</script>

<style lang="scss">
.register-container {
	padding: 0 30rpx;
	background-color: #fff;
	min-height: 100vh;
	
	.header {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100rpx;
		margin-bottom: 40rpx;
		
		.back-btn {
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
			padding: 10rpx 20rpx;
			
			.back-icon {
				font-size: 50rpx;
				color: #333;
			}
		}
		
		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}
	
	.form {
		.input-group {
			margin-bottom: 30rpx;
			
			.label {
				display: block;
				font-size: 28rpx;
				color: #333;
				margin-bottom: 15rpx;
			}
			
			input {
				width: 100%;
				height: 90rpx;
				padding: 0 30rpx;
				border: 1px solid #ddd;
				border-radius: 10rpx;
				font-size: 28rpx;
				background-color: #f8f8f8;
				box-sizing: border-box;
			}
			
			.error {
				display: block;
				color: #ff5555;
				font-size: 24rpx;
				margin-top: 10rpx;
				padding-left: 20rpx;
			}
		}
		
		.agreement {
			margin: 40rpx 0;
			
			checkbox-group {
				label {
					display: flex;
					align-items: center;
					flex-wrap: wrap;
					font-size: 26rpx;
					color: #666;
					
					checkbox {
						transform: scale(0.8);
						margin-right: 10rpx;
					}
					
					.link {
						color: #007AFF;
						margin: 0 8rpx;
					}
				}
			}
			
			.error {
				display: block;
				color: #ff5555;
				font-size: 24rpx;
				margin-top: 10rpx;
				padding-left: 20rpx;
			}
		}
		
		.register-btn {
			width: 100%;
			height: 90rpx;
			line-height: 90rpx;
			background: #007AFF;
			color: #fff;
			border-radius: 45rpx;
			font-size: 32rpx;
			margin-top: 40rpx;
			
			&:disabled {
				background: #999;
				opacity: 0.8;
			}
		}
		
		.login-entry {
			margin-top: 40rpx;
			text-align: center;
			font-size: 28rpx;
			color: #666;
			
			.login-link {
				color: #007AFF;
				margin-left: 10rpx;
			}
		}
	}
}
</style> 